简体   繁体   English

如何有效地编程? 按下按钮时创建相应的活动

[英]How to program efficiently? When pressed button create corresponding activity

I'm new to programming so I have a really easy question. 我是编程新手,所以我有一个非常简单的问题。 Since I do not really know the terms I couldn't find any topic on my problem, so excuse me if this question has been asked before. 由于我真的不知道这个术语我找不到任何关于我的问题的话题,所以请原谅我以前曾经问过这个问题。

My problem is as follows: I'm running an app, created with Eclipse, on an Android machine. 我的问题如下:我在Android机器上运行一个用Eclipse创建的应用程序。 On the first screen I have just a list of buttons: 在第一个屏幕上,我只有一个按钮列表:

layout_main: layout_main:

<Button
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="@string/alpha"
    android:onClick="alpha" />

<Button
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="@string/beta"
    android:onClick="beta"  />

If I press a button then the corresponding activity will start. 如果我按下按钮,则会开始相应的活动。 I programmed the main activity as follow in order to do that: 为了做到这一点,我将主要活动编程如下:

main activity: 主要活动:

public void alpha(View view) {      
    Intent intent = new Intent(this, AlphaActivity.class);
     startActivity(intent); }

public void beta(View view) {       
    Intent intent = new Intent(this, BetaActivity.class);
     startActivity(intent); }

Since I have many buttons, I will have as many times the operation public void as seen above. 因为我有很多按钮,所以我将有多次操作公共空白,如上所示。 Isn't there any way to program it more efficient? 有没有办法让它更有效率? For example: Start new activity, if alpha was selected then start activity alpha, if beta was selected start activity beta, else do nothing. 例如:启动新活动,如果选择了alpha,则启动活动alpha,如果选择了beta,则启动活动测试版,否则不执行任何操作。

You could apply the same listener to each button, not really sure if it's more efficient or even better style, but this will probably work. 你可以对每个按钮应用相同的监听器,不确定它是否更高效甚至更好的风格,但这可能会起作用。 Something like: 就像是:

public void buttonListen(View view)
{
     Class clas;
     int id = view.getId();
     switch(id)
     {
        case R.id.alpha:
            clas = AlphaActivity.class;
            break;
        case R.id.alpha:
            clas = BetaActivity.class;
            break;
        ...
        case R.id.zeta:
            clas = ZetaActivity.class;
            break;
      }
      startActivity(new Intent(this, clas));
}

and assign the corresponding id in the XML as the next answer states. 并在XML中指定相应的id作为下一个答案状态。

you can give every button an id like this : 你可以给每个按钮一个像这样的id:

<Button
    android:id="@+id/alpha"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="@string/alpha"
    />

<Button
    android:id="@+id/beta"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="@string/beta"
      />

then in the main activity you can findviewbyid() to find the two buttons and give buttons onclicklistener,then you implements the onclicklistener like this : 然后在主活动中你可以findviewbyid()找到两个按钮并给出onclicklistener按钮,然后你实现onclicklistener,如下所示:

public void onClick(View v) {
    Intent i = new Intent();
    switch(v.getid()){
        case: R.id.alpha:
            i.setClass(context,AlphaActivity.class);
            break;
        case: R.id.beta:
            i.setClass(context,BetaActivity.class);
            break;
    }
    startActivity(i);
}

hope that helps. 希望有所帮助。

There are many ways you could accomplish your goal. 您可以通过多种方式实现目标。

Note: the best solution would be to add android:id to your layout file, but if for some reason you can't do that, you could use the button text. 注意:最好的解决方案是将android:id添加到您的布局文件中,但如果由于某种原因您无法执行此操作,则可以使用按钮文本。

A very simple (although not great) way to do it without changing your layout file much would be to look at the text on the button, if all buttons have unique text, and perform the action based on that. 如果所有按钮都有唯一的文本,那么在不更改布局文件的情况下执行此操作的非常简单(尽管不是很好)的方法是查看按钮上的文本,并基于此执行操作。

public void onButtonClick(View view)
{
    //Cast the click View into a Button
    Button selectedButton = (Button) view;

    Intent intent = new Intent();

    String buttonText = selectedButton.getText().toString();

    if(buttonText.equals("beta"))
    {
        intent = new Intent(this, BetaActivity.class);
    }
    else if(buttonText.equals("alpha"))
    {
        intent = new Intent(this AlphaActivity.class);
    }

    startActivity(intent);
}

Make sure to set the onClick for each button in the layout file to call this method 确保为布局文件中的每个按钮设置onClick以调用此方法

android:onClick="onButtonClick"

There are many different ways to achieve this and make it simpler. 有许多不同的方法可以实现这一点并使其更简单。 Not a single method will be "the best". 没有一种方法会“最好”。 What you are doing is probably down the list of "what I would not do". 你在做什么可能在“我不会做什么”的列表中。

Don't assign things in XML, it's harder to work with, cannot be really changed at running time and make it less portable when you have to maintain a lot of different layouts. 不要在XML中分配内容,使用起来比较困难,在运行时不能真正改变,并且在必须维护许多不同的布局时使其不那么便携。 Instead… 代替…

This is just ONE way to do it: 这只是一种方法:

Instead of defining the onClick method in the XML, do it programatically. 不是在XML中定义onClick方法,而是以编程方式进行。

Add an android id to your Views: 在您的视图中添加一个android id:

<Button 
android:id="@+id/alpha_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="@string/alpha" />

(the same for all the other buttons) (所有其他按钮都一样)

Note: don't use fill_parent , use match_parent (the former is deprecated and both do the same). 注意:不要使用fill_parent ,请使用match_parent (前者已弃用且两者都相同)。

The in your Activity onCreate() method, right before you setContentView(R.layout.your_above_layout_with_the_buttons); 在您的Activity onCreate()方法中,就在setContentView(R.layout.your_above_layout_with_the_buttons);

You can obtain a reference to each button: 您可以获得每个按钮的引用:

public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.your_above_layout_with_the_buttons);
  final TextView alphaButton = (TextView) findViewById(R.id.alpha_button);
  //etc for the rest
  // now add click listeners:
  alphaButton.setOnClickListener(this);// more on this later
  betaButton.setOnClickListener(this);
  // etc.
}

Now your activity should be: 现在你的活动应该是:

public class YourActivity extends Activity implements View.OnClickListener {

and somewhere in your activity you have to implement: 在您的活动中的某个地方,您必须实施:

@Override
public void onClick(final View view) {
   // which button was clicked? Different ways to tell… a simple one:
   Intent intent;
   switch (v.getId()) {
      case R.id.alpha_button:
         intent = new Intent(this, AlphaActivity.class); 
         break;
      case R.id.beta_button:
         intent = new Intent(this, BetaActivity.class);
         break;
      //etc.
   }
   if (intent != null) {
      startActivity(intent);
   } 
}

For your specific situation, you could could change the way you handle the calls from your buttons, for example, you could give the buttons IDs and check the IDs of the buttons in a single method. 根据您的具体情况,您可以更改按钮处理呼叫的方式,例如,您可以在单个方法中提供按钮ID并检查按钮的ID。

<Button
    android:id="@+id/alpha_button"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="@string/alpha"
    android:onClick="onButtonClick" />

<Button
    android:id="@+id/beta_button"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="@string/beta"
    android:onClick="onButtonClick"  />



public void onButtonClick(View view) {
        Intent intent;
        switch (view.getId()) {
        case R.id.alpha_button:
            intent = new Intent(this, AlphaActivity.class);
            break;
        case R.id.beta_button:
            intent = new Intent(this, BetaActivity.class);
            break;
        default:
            return;
        }
        startActivity(intent);
    }

However, I would suggest that your current code is clear and concise so just leave it as it is. 但是,我建议您当前的代码清晰简洁,所以请保持原样。 There are many ways to solve a problem, especially when it comes to designing software. 有很多方法可以解决问题,特别是在设计软件时。

In general though, programming languages try to balance making code (and more importantly it's function or purpose) easy to read/understand while trying to keep the syntax as concise as possible. 一般而言,编程语言试图平衡使代码(更重要的是它的功能或目的)易于阅读/理解,同时尽量使语法尽可能简洁。 In time you will learn about the advantages and disadvantages of each language and it's syntax, some will be better at solving certain types of problem while being too verbose for solving others. 随着时间的推移,您将了解每种语言的优缺点及其语法,有些人会更好地解决某些类型的问题,而对于解决其他问题则过于冗长。 For now just learn how Java works and try to understand why they have implemented each keyword and syntax element. 现在只需了解Java的工作原理并尝试理解为什么他们已经实现了每个关键字和语法元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM