我正在ADT中创建一些APP,我正在学习一个教程,但我仍然坚持执行按钮将我的文本更改为其他内容。问题是,在教程中,他使用旧版本的ADT,而我的版本更新,因此它不再起作用。代码是这样的:
(包名等)
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
final TextView textOne = (TextView) findViewById(R.id.textik);
Button pushthis = (Button) findViewById(R.id.gombik);}
}
@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 :(得分:0)
这可能是一个更好的例子。 http://www.vogella.com/tutorials/AndroidFragments/article.html https://developer.android.com/training/basics/fragments/creating.html
主要认为我的代码出错了
final TextView textOne = (TextView) findViewById(R.id.textik);
Button pushthis = (Button) findViewById(R.id.gombik);
他们不应该在这里宣布并宣布。如果您使用片段,则应将其移动到片段。下面是一个简单的例子。
public static class PlaceholderFragment extends Fragment implements Button.OnClickListener{
TextView textOne;
Button pushthis;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
textOne = (TextView) rootView.findViewById(R.id.textik);
pushthis = (Button) rootView.findViewById(R.id.gombik);
//set handlers and anything else
pushthis.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.gombik:
textOne.setText("HI");
break;
}
}
}