0
我目前遇到了向父母添加視圖的問題。我不知道如何解決這個問題。我曾看過其他答案,但是沒有任何能夠幫助我。指定的孩子已經有父母異常錯誤
這裏是我的代碼:
int countdown = 0;
CountDownTimer mCountDownTimer;
TableRow tr1;
TableRow tr2;
TextView tv;
protected void createNullUI() {
tr1 = new TableRow(getBaseContext());
tr2 = new TableRow(getBaseContext());
tv = new TextView(this);
tv.setText("Ooops, it looks like the user you were searching for does not exist... You will be redriced back to our homepage shortly =)");
tv.setMaxLines(2);
tv.setTextSize(30);
tv.setSingleLine(false);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ProgressBar mProgressBar = (ProgressBar) inflater.inflate(R.layout.progress, null, false);
mProgressBar.setProgress(countdown);
runOnUiThread(new Runnable() {
public void run() {
//set up the count down timer
mCountDownTimer = new CountDownTimer(3000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + countdown
+ millisUntilFinished);
countdown++;
mProgressBar.setProgress(countdown);
}
@Override
public void onFinish() {
countdown++;
mProgressBar.setProgress(countdown);
}
};
mCountDownTimer.start();
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
tr1.setLayoutParams(tableRowParams);
tr2.setLayoutParams(tableRowParams);
tr1.addView(tv);
tr2.addView(mProgressBar);
((ViewGroup)tr1.getParent()).removeView(tr1);
((ViewGroup)tr2.getParent()).removeView(tr2);
tableScrollView.addView(tr1); // <--- Error here
tableScrollView.addView(tr2);
}
});
}
例外:
08-30 02:44:37.446: E/AndroidRuntime(17698): FATAL EXCEPTION: main
08-30 02:44:37.446: E/AndroidRuntime(17698): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
08-30 02:44:37.446: E/AndroidRuntime(17698): at android.view.ViewGroup.addViewInner(ViewGroup.java:3365)
08-30 02:44:37.446: E/AndroidRuntime(17698): at android.view.ViewGroup.addView(ViewGroup.java:3236)
08-30 02:44:37.446: E/AndroidRuntime(17698): at android.widget.TableLayout.addView(TableLayout.java:429)
08-30 02:44:37.446: E/AndroidRuntime(17698): at android.view.ViewGroup.addView(ViewGroup.java:3181)
08-30 02:44:37.446: E/AndroidRuntime(17698): at android.widget.TableLayout.addView(TableLayout.java:411)
08-30 02:44:37.446: E/AndroidRuntime(17698): at android.view.ViewGroup.addView(ViewGroup.java:3157)
08-30 02:44:37.446: E/AndroidRuntime(17698): at android.widget.TableLayout.addView(TableLayout.java:402)
08-30 02:44:37.446: E/AndroidRuntime(17698): at com.tabcards.android.Search$2.run(Search.java:197)
08-30 02:44:37.446: E/AndroidRuntime(17698): at android.os.Handler.handleCallback(Handler.java:725)
08-30 02:44:37.446: E/AndroidRuntime(17698): at android.os.Handler.dispatchMessage(Handler.java:92)
08-30 02:44:37.446: E/AndroidRuntime(17698): at android.os.Looper.loop(Looper.java:158)
08-30 02:44:37.446: E/AndroidRuntime(17698): at android.app.ActivityThread.main(ActivityThread.java:5751)
08-30 02:44:37.446: E/AndroidRuntime(17698): at java.lang.reflect.Method.invokeNative(Native Method)
08-30 02:44:37.446: E/AndroidRuntime(17698): at java.lang.reflect.Method.invoke(Method.java:511)
08-30 02:44:37.446: E/AndroidRuntime(17698): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
08-30 02:44:37.446: E/AndroidRuntime(17698): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
08-30 02:44:37.446: E/AndroidRuntime(17698): at dalvik.system.NativeStart.main(Native Method)
編輯:連簡單的東西,因爲這將引發錯誤:
TextView tv1 = new TextView(getBaseContext());
tv1.setText("null input");
tableScrollView.addView(tv1);
告訴我,如果你需要的代碼全班同學
編輯:全班同學:
//removed imports & package
public class Search extends ActionBarActivity {
TableLayout tableScrollView;
String value;
JSONObject jObject;
private Bitmap profilepic;
private Drawable bgpic;
TableLayout tr;
TableRow trcard;
TableLayout tlcard;
int bgcolor = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
tr = (TableLayout) findViewById(R.id.TableLayout1);
tr.setBackgroundColor(0);
// bgpic.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getString("id");
}
trcard = new TableRow(getBaseContext());
tlcard = new TableLayout(getBaseContext());
ActionBar ab = getSupportActionBar();
ab.setTitle(value);
tableScrollView = (TableLayout) findViewById(R.id.tableScrollView);
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
jObject = getJson("http://www.tabcards.com/req/androidapi/L2o30H8JlFMtFYHW3KLxkts20ztc5Be6Z6m6v315/json/"
+ value);
if (jObject != null) {
try {
if (!jObject.getString("profilepic").equals("")) {
profilepic = BitmapFactory.decodeStream(new URL(
jObject.getString("profilepic"))
.openConnection().getInputStream());
}
if (!jObject.getString("bg").equals("")) {
if (jObject.getString("bg").toString()
.startsWith("#")) {
System.out.println(jObject.getString("bg"));
bgcolor = Color.parseColor(jObject
.getString("bg"));
} else {
profilepic = BitmapFactory
.decodeStream(new URL(jObject
.getString("bg"))
.openConnection()
.getInputStream());
}
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
createUI(jObject);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} else {
//TextView tv1 = new TextView(getBaseContext());
//tv1.setText("null input");
//tableScrollView.addView(tv1);
//createNullUI();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent returnBtn = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(returnBtn);
}
}
});
thread.start();
System.out.println("complete");
}
int countdown = 0;
CountDownTimer mCountDownTimer;
TableRow tr1;
TableRow tr2;
TextView tv;
protected void createNullUI() {
tr1 = new TableRow(getBaseContext());
tr2 = new TableRow(getBaseContext());
tv = new TextView(this);
tv.setText("Ooops, it looks like the user you were searching for does not exist... You will be redriced back to our homepage shortly =)");
tv.setMaxLines(2);
tv.setTextSize(30);
tv.setSingleLine(false);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ProgressBar mProgressBar = (ProgressBar) inflater.inflate(R.layout.progress, null, false);
mProgressBar.setProgress(countdown);
runOnUiThread(new Runnable() {
public void run() {
//set up the count down timer
mCountDownTimer = new CountDownTimer(3000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + countdown
+ millisUntilFinished);
countdown++;
mProgressBar.setProgress(countdown);
}
@Override
public void onFinish() {
countdown++;
mProgressBar.setProgress(countdown);
}
};
mCountDownTimer.start();
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
TableLayout.LayoutParams tableRowParams1 = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
tr1.setLayoutParams(tableRowParams);
//tr2.setLayoutParams(tableRowParams1);
tr1.addView(tv);
tr2.addView(mProgressBar);
((ViewGroup)tr1.getParent()).removeView(tr1);
((ViewGroup)tr2.getParent()).removeView(tr2);
tableScrollView.addView(tr1);
//tableScrollView.addView(tr2);
}
});
}
@SuppressLint("NewApi")
private void createUI(JSONObject jObject) throws JSONException {
int absIndex = 0;
System.out.println(jObject.getString("bg") + "createUI");
if (android.os.Build.VERSION.SDK_INT >= 16) {
if (bgcolor != -1) {
System.out.println("color: " + bgcolor);
tr.setBackgroundColor(bgcolor);
} else if (bgpic != null) {
tr.setBackground(bgpic);
}
}
boolean last = false;
String lastString = WhoIsLast(jObject);
System.out.println(lastString);
String name = jObject.getString("name");
String facebook = jObject.getString("facebook");
String twitter = jObject.getString("twitter");
String phone = jObject.getString("phone");
String email = jObject.getString("email");
if (name != "") {
insertElement(name, "name", absIndex++, profilepic, true, false);
}
;
if (!facebook.equals("")) {
if (facebook.equals(lastString)) {
last = true;
}
insertElement(facebook, "facebook", absIndex,
BitmapFactory.decodeResource(getResources(),
R.drawable.facebook), false, last);
absIndex += 2;
}
if (!twitter.equals("")) {
if (twitter.equals(lastString)) {
last = true;
}
insertElement(twitter, "twitter", absIndex,
BitmapFactory.decodeResource(getResources(),
R.drawable.twitter), false, last);
absIndex += 2;
}
if (!phone.equals("")) {
if (phone.equals(lastString)) {
last = true;
}
insertElement(phone, "phone", absIndex,
BitmapFactory.decodeResource(getResources(),
R.drawable.phone), false, last);
absIndex += 2;
}
if (!email.equals("")) {
if (email.equals(lastString)) {
last = true;
}
insertElement(email, "email", absIndex,
BitmapFactory.decodeResource(getResources(),
R.drawable.email), false, true);
absIndex += 2;
}
trcard.setBackground(getResources()
.getDrawable(R.drawable.bg_card/* abc_menu_dropdown_panel_holo_light */));
trcard.addView(tlcard);
tr.setPadding(0, 0, 0, 0);
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
int[] attrs = { android.R.attr.dividerVertical };
TypedArray typedArray = getApplicationContext().obtainStyledAttributes(
attrs);
Drawable divider = typedArray.getDrawable(0);
typedArray.recycle();
tableRowParams.setMargins(20, 20, 20, 0);
trcard.setLayoutParams(tableRowParams);
tlcard.setDividerDrawable(divider);
tlcard.setDividerPadding(4);
tableScrollView.addView(trcard);
}
private String WhoIsLast(JSONObject j) throws JSONException {
if (j.getString("facebook").equals("")) {
return "";
}
if (j.getString("twitter").equals("")) {
return "facebook";
}
if (j.getString("email").equals("")) {
return "twitter";
}
if (j.getString("phone").equals("")) {
return "email";
}
return "";
}
/*
* private void createMainImage() { LayoutInflater inflater =
* (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View
* newRow = inflater.inflate(R.layout.row, null, false);
* newRow.setLayoutParams(new TableRow.LayoutParams(
* TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
* TextView dataTextView = (TextView) newRow
* .findViewById(R.id.rowTextView); dataTextView.setVisibility(View.GONE);
* ImageView iv = (ImageView) newRow.findViewById(R.id.imageView);
* DisplayMetrics metrics =
* getBaseContext().getResources().getDisplayMetrics(); int width =
* metrics.widthPixels; int height = metrics.heightPixels;
* iv.setImageBitmap(getCroppedBitmap(Bitmap.createScaledBitmap(profilepic,
* width-300, width-300, true), iv));
*
* tableScrollView.addView(newRow, 0); }
*/
private void insertElement(String data, String key, int i, Bitmap bm,
boolean flag, boolean b) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newRow = inflater.inflate(R.layout.row, null, false);
newRow.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
AutoResizeTextview dataTextView = (AutoResizeTextview) newRow
.findViewById(R.id.rowTextView);
dataTextView.setText("\t " + data);
ImageView iv = (ImageView) newRow.findViewById(R.id.imageView);
newRow.setId(i);
newRow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
TextView tv = null;
ArrayList<View> allViewsWithinMyTopView = getAllChildren(view);
for (View child : allViewsWithinMyTopView) {
if (child instanceof TextView) {
tv = (TextView) child;
}
}
String prefix = "";
switch (view.getId()) {
case 1:
prefix = "https://www.facebook.com/";
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri
.parse(prefix + tv.getText().toString()));
startActivity(browserIntent);
break;
case 2:
prefix = "https://www.twitter.com/";
Intent browserIntent2 = new Intent(Intent.ACTION_VIEW, Uri
.parse(prefix
+ tv.getText().toString()
.replace("%20", "")));
startActivity(browserIntent2);
break;
case 3:
Intent phoneIntent = new Intent(Intent.ACTION_DIAL, Uri
.parse("tel:"
+ tv.getText().toString()
.replace("%20", "")));
startActivity(phoneIntent);
break;
case 4:
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setType("message/rfc822");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
emailIntent.putExtra(Intent.EXTRA_TEXT, "");
emailIntent.setData(Uri.parse("mailto:"
+ tv.getText().toString()));
emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(emailIntent);
break;
}
}
});
View v = new View(this);
v.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT, 1));
v.setBackgroundColor(Color.argb(15, 111, 111, 111));
dataTextView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int sf = 1;
if (i == 0) {
sf = 2;
dataTextView.setShadowLayer(3, 0, 0, Color.BLACK);
dataTextView.setTextColor(getResources().getColor(R.color.white));
}
if (bm == null) {
iv.setVisibility(View.GONE);
} else {
iv.setImageBitmap(getCroppedBitmap(Bitmap.createScaledBitmap(
Bitmap.createScaledBitmap(bm, bm.getWidth()/2 * sf,
bm.getWidth()/2 * sf, true),
dataTextView.getMeasuredHeight() * sf,
dataTextView.getMeasuredHeight() * sf, true), iv, key));
}
if (flag) {
dataTextView.setTextSize(40);
tableScrollView.addView(newRow, i);
} else {
tlcard.addView(newRow, i - 1);
if (!b) {
tlcard.addView(v, i);
}
}
}
public static boolean useLoop(String[] arr, String targetValue) {
for (String s : arr) {
if (s.equals(targetValue))
return true;
}
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJson(String url) {
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
// HTTP
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
return null;
}
// Read response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString().replace("[", "");
System.out.println(result);
if (result.equals("CARD NOT FOUND\n")) {
System.out.println(result);
return null;
}
} catch (Exception e) {
return null;
}
// Convert string to object
try {
jsonObject = new JSONObject(result.replace("]", ""));
} catch (JSONException e) {
return null;
}
return jsonObject;
}
private ArrayList<View> getAllChildren(View v) {
if (!(v instanceof ViewGroup)) {
ArrayList<View> viewArrayList = new ArrayList<View>();
viewArrayList.add(v);
return viewArrayList;
}
ArrayList<View> result = new ArrayList<View>();
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
ArrayList<View> viewArrayList = new ArrayList<View>();
viewArrayList.add(v);
viewArrayList.addAll(getAllChildren(child));
result.addAll(viewArrayList);
}
return result;
}
public static Bitmap getCroppedBitmap(Bitmap bitmap, ImageView iv,
String key) {
if (key == "email" || key == "facebook" || key == "twitter"
|| key == "phone") {
return bitmap;
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int radius = Math.min(h/2, w/2);
Bitmap output = Bitmap.createBitmap(w + 8, h + 8, Config.ARGB_8888);
Paint p = new Paint();
p.setAntiAlias(true);
Canvas c = new Canvas(output);
c.drawARGB(0, 0, 0, 0);
p.setStyle(Style.FILL);
c.drawCircle((w/2) + 4, (h/2) + 4, radius, p);
p.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
c.drawBitmap(bitmap, 4, 4, p);
p.setXfermode(null);
p.setStyle(Style.STROKE);
p.setColor(Color.BLACK);
p.setStrokeWidth(1);
c.drawCircle((w/2) + 4, (h/2) + 4, radius, p);
return output;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, menu);
return true;
}
}
全班有助於 – 2014-08-30 04:24:31
@Rod_Algonquin確定將在早上做。這是否有助於圖標即使被替換爲其他圖像也不會改變? – gedr 2014-08-30 04:30:20
@Rod_Algonquin好的,我添加了全班。另外,如果它有幫助,當我保存並運行應用程序時,它說它已被部署,並且不需要重新安裝(?)。我不知道這是否會影響到它,我也想問問你是否知道解決方法。 – gedr 2014-08-30 17:29:49