2014-04-19 4 views
1

После добавления действия кнопки в android Application.java приложение закрывается, к сожалению. , пожалуйста, помогите в разрешении. какой код мне не хватает здесь? ????Android setOnClickListener не работает

public class MainActivity extends ActionBarActivity { 


int counter; 
Button add, sub; 
TextView display; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    counter = 0; 
    add = (Button) findViewById(R.id.bAdd); 
    sub = (Button) findViewById(R.id.bSub); 
    display = (TextView) findViewById(R.id.textDisp); 

    add.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // Perform action on click 
      counter++; 
     } 
    }); 

    if (savedInstanceState == null) { 
     getSupportFragmentManager().beginTransaction() 
       .add(R.id.container, new PlaceholderFragment()) 
       .commit(); 
    } 
} 


@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(); 
    if (id == R.id.action_settings) { 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

/** 
* A placeholder fragment containing a simple view. 
*/ 
public static class PlaceholderFragment extends Fragment { 

    public PlaceholderFragment() { 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
     return rootView; 
    } 
} 

} 
+0

Где трассировки стеки? – nKn

+0

отправьте свой logcat. –

+1

Сообщение activity_main.xml – Onik

ответ

3

Кажется, вы построили свои взгляды внутри fragment_main.xml и не activity_main.xml.

Когда вы первый создать новый андроид проект, у вас есть эти файлы, которые автоматически создаются и открытые:

enter image description here

Затем, когда вы начинаете, вы добавляете взгляды (например: а TextView) внутри fragment_main.xml файл. В то время как вы пытались сделать в основном события с этой точки зрения внутри Activity, что-то вроде этого:

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); // Using layout activity_main.xml 

     // You try to set a simple text on the view (TextView) previously added 
     TextView text = (TextView) findViewById(R.id.textView1); 
     text.setText("Simple Text"); // And you get an error here! 

     /* 
     * You do an fragment transaction to add PlaceholderFragment Fragment 
     * on screen - this below snippnet is automatically created. 
     */ 
     if(savedInstanceState == null) { 
      getSupportFragmentManager().beginTransaction() 
        .add(R.id.container, new PlaceholderFragment()).commit(); 
     } 
    } 

Вы не можете запустить приложение или иногда у вас есть только белый экран, потому что взгляды, которые вы пытались позвонить/дисплей находятся в неправильном расположении.

Переместите все свои вещи внутри метода onCreateView в класс фрагментов. Вызовы и сделайте что-то в связанном фрагменте, а не родительском действии.


Например, для случая:

public static class PlaceholderFragment extends Fragment { 

    int counter; 
    Button add, sub; 
    TextView display; 

    public PlaceholderFragment() { 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main, container, false); 

     counter = 0; 
     // Don't forget to attach your view to the inflated view as "rootView.findViewById()" 
     add = (Button) rootView.findViewById(R.id.bAdd); 
     sub = (Button) rootView.findViewById(R.id.bSub); 
     display = (TextView) rootView.findViewById(R.id.textDisp); 

     add.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) { 
        // Perform action on click 
        counter++; 
       } 
     }); 
     return rootView; 
    } 
} 
+0

да, у меня есть кнопки в фрагменте _main.xml – user3472293

+0

@ user3472293 Затем вам нужно найти свои взгляды по своим идентификаторам ** внутри onCreateView ** в свой фрагмент и * * не внутри onCreate ** метод из вашей деятельности. Смотрите мой ответ, это именно то, что вам нужно сделать. – Fllo

1

я получил решение, и я проверил это слишком

проблема не только перемещение кода в

но также я должен использовать следующее после перемещения кода

add = (Button) rootView.findViewById (R.id.bAdd); 
    sub = (Button) rootView.findViewById(R.id.bSub); 
    display = (TextView) rootView.findViewById(R.id.tvDisplay); 

вместо следующего

add = (Button) findViewById (R.id.bAdd); 
      sub = (Button) findViewById(R.id.bSub); 
      display = (TextView) findViewById(R.id.tvDisplay); 

я надеюсь, что любое тело комментария здесь для объяснения такого поведения, пожалуйста

Смежные вопросы