我对Android完全陌生。 我只想要一个执行任务的按钮,但互联网上的示例代码不起作用。 即使eclipse没有出现任何错误,我也无法在我的设备上运行此应用程序。这是代码:
package com.example.myfirstapp;
import com.example.myfirstapp.R;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
@SuppressLint("ValidFragment")
public class MainActivity extends ActionBarActivity {
static Button btn;
@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();
}
}
@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 implements View.OnClickListener {
public PlaceholderFragment() {
}
public void onClick(View v){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.sicioldrart.com"));
startActivity(browserIntent);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
btn=(Button) getView().findViewById(R.id.bottone);
btn.setOnClickListener(this);
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
感谢您的帮助
答案 0 :(得分:4)
在查找按钮之前,您需要有一个充气的视图。
移动这个:
btn=(Button) getView().findViewById(R.id.bottone);
btn.setOnClickListener(this);
以下
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
并使用getView()
rootView
答案 1 :(得分:1)
btn=(Button) getView().findViewById(R.id.bottone);
btn.setOnClickListener(this);
这两行将在
之后出现View rootView = inflater.inflate(R.layout.fragment_main, container, false);
并用rootView
替换getView()btn=(Button) rootView.findViewById(R.id.bottone);
btn.setOnClickListener(this);