Mohammad
Mohammad

Reputation: 41

Android: getLayoutInflater Not work in static class

I want use getLayoutInflater in static class

But not work after run this code :

MainActivity.java

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        LinearLayout post = (LinearLayout) findViewById(R.id.post);
        Commands.readD(post);
    }
}

Commands.java

public class Commands {

    public static void readD(LinearLayout viewPost) {
        LayoutInflater inflater = getLayoutInflater();
        final View viewIn = inflater.inflate(R.layout.viewIn, null);
        final TextView txtNd = (TextView) viewIn.findViewById(R.id.txtNd);
        viewMain.addView(viewIn);
    }
}

This line error is :

The method getLayoutInflater() is undefined for the type Commands

Upvotes: 0

Views: 2033

Answers (3)

xiaohu Wang
xiaohu Wang

Reputation: 909

The error occurred because you can not achieve LayoutInflater without Context. I suggest you pass a Context param in your method such as:

  public class Commands {

    public static void readD(LinearLayout viewMain,Context context) {
        LayoutInflater inflater =LayoutInflater.from(context);
        final View viewIn = inflater.inflate(R.layout.viewIn, null);
        final TextView txtNd = (TextView) viewIn.findViewById(R.id.txtNd);
        viewMain.addView(viewIn);
    }
}

Upvotes: 1

M D
M D

Reputation: 47807

Actually you need context in your static class

public static void readD(LinearLayout viewPost,Activity context) {

LayoutInflater inflater = context.getLayoutInflater()
 ......
}

OR

another way is

public static void readD(LinearLayout viewPost) {
  LayoutInflater inflater = viewPost.getContext().getLayoutInflator();
 //do your stuff
}

as @ρяσѕρєя K mention

Upvotes: 2

Nagaraju V
Nagaraju V

Reputation: 2757

pass Activity through method

public static void readD(LinearLayout viewPost,Activity context) {
      LayoutInflater inflater = context.getLayoutInflater();
     //do your stuff
}

And in onCreate()

 Commands.readD(post,this);

OR

public static void readD(LinearLayout viewPost) {
      LayoutInflater inflater = viewPost.getContext().getLayoutInflator();
     //do your stuff
}

as ρяσѕρєя K mention..

Hope this will helps you.

Upvotes: 5

Related Questions