A,B和C类仅位于src中,而MainActivity.class
位于source/com/example/TestApplication
中。
MainActivity似乎没有看到其他类,因为它们不在同一个位置/包中。如何调用其他类的方法在MainActivity中工作。
以下是我的代码示例:我想在MainActivity中运行UseActivity方法
public class UseActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public String sEntries(View view)
{
DatabaseHandler db = new DatabaseHandler(this);
String sfinal = "";
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "9100000000"));
db.addContact(new Contact("Srinivas", "9199999999"));
db.addContact(new Contact("Tommy", "9522222222"));
db.addContact(new Contact("Karthik", "9533333333"));
switch (view.getId())
{
case R.id.button1:
EditText dbText = (EditText) findViewById(R.id.editText1);
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts)
{
sfinal = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
// Writing Contacts to sfinal
Log.d("Name: ", sfinal);
dbText.setText(sfinal);
}
break;
}
return sfinal;
}
}
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@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;
}
UseActivity u = new UseActivity();
{
u.sEntries(View view);
} /////////////////////////// this doesnt work, program underlines UseActivity in red giving error and doesnt see it as another class (maybe because of package)
答案 0 :(得分:2)
首先,在MainActivity中导入User Activity类
import your.package.UseActivity;
其次,在OnCreate中,实例化您的UseActivity类。
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UseActivity u = new UseActivity();
etc...
}
答案 1 :(得分:1)
您需要导入类A,B和C.默认情况下,eclipse中用于自动导入的快捷方式至少为:
CNTRL + SHIFT + O
我按了这些键这么多次字母已经磨损了。
答案 2 :(得分:0)
你必须在AndroidManifest.xml中添加第二个活动,然后像毛解释||那样做使用类似下面的内容
public void YourAction() {
startActivity(new Intent("youpackage.SecondActivity"));
}
<activity
android:label="Second Activity"
android:name=".SecondActivity" >
<intent-filter >
<action android:name="yourpackage.SecondActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>