I'm trying to create a simple fragment that merely displays an image when clicked. I'm getting numerous errors inlcuding "the method findViewbyId(int) is undefined for the type ExampleFragment", "Inflater cannot be resolved", and "imageview_main cannot be resolved or is not a field." imageview_main is a layout I have created, imageView1 is an image contained in that layout. Here is the fragment code:
package com.firstproject.simplemenu;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.app.Fragment;
import android.widget.ImageView;
public class ExampleFragment extends Fragment {
Button button;
ImageView image;
public ExampleFragment() {
}
public static ExampleFragment newInstance() {
return new ExampleFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ImageView imageview = (ImageView)findViewById(R.id.imageView1);
return Inflater.inflate(R.layout.iamgeview_main, container, false);
}
public void addListenerOnButton() {
button = (Button) findViewById(R.id.btnChangeImage);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
image.setImageResource(R.drawable.eagle);
}
});
}
I added the following modifications to your code ;
1) Import Fragment from support library(important if running on early versions of android);
2) Insted of Inflater I used the inflater received as method param;
3) I created a method findViewById that can be used in this fragment;
4) I moved some of the initialisation code in the method onActivityCreated ; Here
you cand find more about that method ;
findViewById is a method in the class Activity. To avoid passing an instance of the entire activity use a WeakRefence (see http://developer.android.com/reference/java/lang/ref/WeakReference.html) for example