0

对 android 编程来说相当新,并且在单击按钮时无法更改字符串值“通道”。在尝试关闭 onCreate 时遇到问题,但它似乎只能让我在活动结束时关闭它。我收到“令牌“}”的错误。如果我尝试在其他地方关闭它,请删除。尽管这可能很简单,但我很难理解这一点。

public class MainActivity extends Activity { 

    String channel = "bbc1";

    // This method creates main application view
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState); 
        // Set view
        setContentView(R.layout.main);
        final ViewSwitcher switcher = (ViewSwitcher)findViewById(R.id.ViewSwitcher1);
        Button bbcButton = (Button) findViewById(R.id.bbcButton);
        Button bbc2Button = (Button) findViewById(R.id.bbc2Button);



        bbcButton.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                channel = "bbc1";
                switcher.showNext();    
            }   
        });


        bbc2Button.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                channel = "bbc2";
                switcher.showNext();
            }
        });


        try{
            // This line creates RSS reader
            RssReader rssReader = new RssReader("http://bleb.org/tv/data/rss.php?ch="+channel+"&day=0");

            // This line gets a ListView from main view
            ListView tvItems = (ListView) findViewById(R.id.listMainView);

            // This line creates a list adapter
            ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this,android.R.layout.simple_list_item_1, rssReader.getItems());

            // This line sets list adapter for the ListView
            tvItems.setAdapter(adapter);


        } catch (Exception e) {
            Log.e("Tv RSS Reader", e.getMessage());
        }

    }
}
4

1 回答 1

0

我猜您想在按下按钮时更改 RSS 提要。但是由于您在 onCreate 中获取 RSS 信息,因此即使您按下按钮,也不会更新数据。但是您正在更改字符串通道的值。

onCreate 仅在您创建活动时调用一次!

尝试将 try 语句移动到一个单独的方法中,并在您的两个 onClickListener 中调用此方法。

    bbc2Button.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            channel = "bbc2";
            updateRSS();
            switcher.showNext();
        }
    });

    public void updateRSS(){
        try{
           // This line creates RSS reader
           RssReader rssReader = new RssReader("http://bleb.org/tv/data/rss.php?ch="+channel+"&day=0");

           // This line gets a ListView from main view
           ListView tvItems = (ListView) findViewById(R.id.listMainView);

           // This line creates a list adapter
           ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this,android.R.layout.simple_list_item_1, rssReader.getItems());

           // This line sets list adapter for the ListView
           tvItems.setAdapter(adapter);


        } catch (Exception e) {
           Log.e("Tv RSS Reader", e.getMessage());
    }
于 2013-04-08T13:49:57.717 回答