2016-06-14 3 views
0

조각 및 프로그램 클릭 이벤트에있는 버튼에 어떻게 액세스합니까? 나는 이것에 비슷한 질문이 있다는 것을 알고 있지만, 나는 그들이 제공 한 해결책을 시도했지만 그들은 나를 위해 일하지 않았다. 나는 항상 도달 할 수없는 오류가 발생합니다.어떻게 조각에있는 단추에 액세스 할 수 있습니까?

요구 사항; 기본적으로 나는 XML에 두 개의 버튼이 있는데, 하나는 보이지 않고 다른 하나는 보이지 않는다. 보이는 버튼을 클릭하여 보이지 않게 한 다음 보이지 않는 버튼을 보이게하려고합니다.

안드로이드 스튜디오의 기본 navaigation drawer 활동을 편집하여 파편을 만들고 있습니다. 범용 탐색 창을 사용하려고합니다. 기본 클래스를 쉽게 편집 할 수 있습니다.

활동 코드

package co.timetrax.drawer; 

import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.view.View; 
import android.support.design.widget.NavigationView; 
import android.support.v4.view.GravityCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBarDrawerToggle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.Button; 

import butterknife.Bind; 
import butterknife.ButterKnife; 

public class MainActivity extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener { 

    NavigationView navigationView = null; 
    Toolbar toolbar = null; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     //setting fragments 
     MainFragment fragment = new MainFragment(); 
     android.support.v4.app.FragmentTransaction fragmentTransaction = 
       getSupportFragmentManager().beginTransaction(); 
     fragmentTransaction.replace(R.id.fragment_container, fragment); 
     fragmentTransaction.commit(); 

     toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
      } 
     }); 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
       this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
     drawer.setDrawerListener(toggle); 
     toggle.syncState(); 

     navigationView = (NavigationView) findViewById(R.id.nav_view); 
     navigationView.setNavigationItemSelectedListener(this); 

    } 

    @Override 
    public void onBackPressed() { 
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     if (drawer.isDrawerOpen(GravityCompat.START)) { 
      drawer.closeDrawer(GravityCompat.START); 
     } else { 
      super.onBackPressed(); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    @SuppressWarnings("StatementWithEmptyBody") 
    @Override 
    public boolean onNavigationItemSelected(MenuItem item) { 
     // Handle navigation view item clicks here. 
     int id = item.getItemId(); 

     if (id == R.id.nav_camera) { 
      // Handle the camera action 
      MainFragment fragment = new MainFragment(); 
      android.support.v4.app.FragmentTransaction fragmentTransaction = 
        getSupportFragmentManager().beginTransaction(); 
      fragmentTransaction.replace(R.id.fragment_container, fragment); 
      fragmentTransaction.commit(); 
     } else if (id == R.id.nav_gallery) { 

     } else if (id == R.id.nav_slideshow) { 

     } else if (id == R.id.nav_manage) { 

     } else if (id == R.id.nav_share) { 

     } else if (id == R.id.nav_send) { 

     } 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    } 
} 

조각 코드 여기

package co.timetrax.drawer; 


import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 

import butterknife.Bind; 
import butterknife.ButterKnife; 



/** 
* A simple {@link Fragment} subclass. 
*/ 
public class MainFragment extends Fragment implements View.OnClickListener { 

    public MainFragment() { 
     // Required empty public constructor 
    } 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     return inflater.inflate(R.layout.fragment_main, container, false); 

    } 

    @Override 
    public void onClick(View v) { 

    } 

} 

는 XML 단편이고;

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="co.timetrax.drawer.MainFragment"> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="MAIN" 
     android:padding="8dp" 
     android:textColor="#fff" 
     android:background="@color/colorPrimary" 
     android:textSize="28sp" 
     android:id="@+id/main_button" 
     android:layout_centerVertical="true" 
     android:layout_centerHorizontal="true" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="second" 
     android:visibility="gone" 
     android:padding="8dp" 
     android:textColor="#fff" 
     android:background="@color/colorPrimary" 
     android:textSize="28sp" 
     android:id="@+id/second_button" 
     android:layout_centerVertical="true" 
     android:layout_centerHorizontal="true" /> 


</RelativeLayout> 
+0

버튼에 리스너를 설정하지 않았고'onClick' 메소드에 코드도 없습니다. – Rohit5k2

+0

그건 내 질문의 요점이다. 나는 청취자를 설정했지만 그들은 안드로이드 스튜디오에서 redflagged했다. – mpanga

답변

0

변경이이 방법

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_main, container, false); 
    Button mainButton = (Button) view.findViewById(R.id.main_button); 
    //proceed to add the listener in a regular way 
    //I will not write that code here; mainButton.setOnClickListener ...... 
    return view; 

} 

그리고 모든 Button 또는 당신이 필요로하는 다른 UI 요소에 대해이 작업을 수행합니다.

+0

나는 이미 이것을 시도했다. mainButton.setOnclickListener (this)를 작성할 때. (this)는 빨간색으로 밑줄이 그어져 있으며 오류는 도달 할 수 없다는 것입니다. – mpanga

+0

그리고? 이것은 효과가 있었음에 틀림 없다. – Vucko

+0

작동하지 않아 다시 시도하십시오. 어딘가에서 뭔가 잘못한 게 틀림 없어. 그러나 나는 위의 답처럼 정확히 쓰고있다. – mpanga

-1

조각 내 어디에서나 getView()을 호출하여 루트보기를 얻을 수 있습니다. 그러면 다음과 같이 호출 할 수 있습니다 :

View root = getView(); 
Button myButton = (Button) root.findViewById(R.id./*id*/); 
myButton.setVisibility(View.INVISIBLE); 
+0

'getView()'가 null을 반환 할 수 있기 때문에'onCreateView'에서 뷰를 팽창시킬 때 더 좋은 방법입니다. – Vucko

+0

실제로, 그것에 대해 상세히 설명해야합니다. 게다가,'findViewById'를 덜 호출하는 것이 좋습니다. 그러나 그것은 할 수있는 일입니다. – Sunshinator

+0

답변 해 주셔서 감사합니다. 나는 실제로 이것을 시도했고 Vucko가 언급 한 오류를 얻었다. – mpanga

관련 문제